/**
 * Created by zhanglihe on 15/11/7.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog',
    'ckeditor'
], function( $, common, ready, Collection, template, Model, dialog,ckeditor ) {
    var index = function() {
        this.init();
    };
    index.prototype = {
        init: function() {
            //loading();
            var _this =this;
            $.ajax({
                url: _global.url.api + 'article_info',
                data: {id: id},
                type: 'get',
                async: false,
                success: function(res) {
                    if(res.code == 0) {
                        _this.set('info', res.data);
                    }
                }
            });
            this.fetch();
            this.event();
        },
        fetch:function(){
            var _this = this;
            var html=template('add-tpl',this.info);
            $("#main-view").html(html);
            $('[name="details"]').ckeditor();
            if(this.info.type==1){
                $("#tp_url").hide();
                $("#tp_content").show();
            }else{
                $("#tp_url").show();
                $("#tp_content").hide();
            }
            if(this.info.is_goods==1){
                $("#div_content_goods").show();
                $.each(this.info.goods,function(i,v){
                    $("#goods-item").append(template('goods-item-tpl',{goods_id:v.id, goods_name:v.name,price:v.price,listorder: v.listorder}));
                });
                $("#div_goods").show();
                $('.goods-item-del').on('click', function(e) {
                    e.preventDefault();
                    $(this).parent().parent().remove();

                });
            }else{
                $("#div_content_goods").hide();
                $("#div_goods").hide();
            }

        },
        set: function($k, $v) {
            this[$k] = $v;
        },
        event: function() {
            this.data = {};
            var _this = this;
            $("input[name='is_goods']").on("click",function(e){
                if($(this).val()==1){
                    $("#div_content_goods").show();
                    $("#div_goods").show();
                }else{
                    $("#div_content_goods").hide();
                    $("#div_goods").hide();
                }
            })
            $("#btn-search").on("click",function(e){
                e.preventDefault();

                _this.select_goods(e);
            });
            $("#type").on("change",function(e){
                if($(this).val()==1){
                    $("#tp_url").hide();
                    $("#tp_content").show();
                }else{
                    $("#tp_url").show();
                    $("#tp_content").hide();
                }
            });
            //保存
            $("#btn_save").on("click",function() {
                _this.data.title = $.trim($("#title").val());
                if(_this.data.title==''){
                    Alert({msg:'请输入标题',type:'error'});
                    return false;
                }
                _this.data.desc = $.trim($("#desc").val());
                _this.data.img = $("input[name='imgs']").val();
                if(_this.data.img==''||_this.data.img==undefined){
                    Alert({msg:'请传入一张图片',type:'error'});
                    return false;
                }
                _this.data.type =$("#type").val();
                if(_this.data.type==2){
                    _this.data.url = $.trim($("#url").val());
                    if(_this.data.url==''){
                        Alert({msg:'请输入外链',type:'error'});
                        return false;
                    }
                }
                if(_this.data.type==1){
                    _this.data.details = $.trim($("#details").val());
                    if(_this.data.details==''){
                        Alert({msg:'请输入内容',type:'error'});
                        return false;
                    }
                }
                _this.data.listorder = $("#listorder").val();
                _this.data.is_goods =$("input[name='is_goods']:checked").val();
                if(_this.data.is_goods==1){
                    var goods=new Array();
                    $(".goods_id").each(function(){
                        if($(this).val()){
                            goods.push($(this).val());
                        }
                    });
                    if(goods==''){
                        Alert({msg:'请选择要关联的商品',type:'error'});
                        return false;
                    }
                    var lisrorders = new Array();
                    $("input[name='lisrorders']").each(function(e){
                        lisrorders.push($(this).val());
                    });
                    _this.data.goods =goods.join(',');
                    _this.data.lisrorders =lisrorders.join(',');
                }
                _this.data.id =id;
                if(new Model({
                        url: _global.url.api + 'article',
                        data:_this.data
                    }).put()){
                    _this.fetch();
                }

            });
            $('body').on('click', '#btn-upload', function(e) {
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function() {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                    }, cancel: function() {}
                });
                _this.upload_dialog.show();
            });
        },

        change: function(e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        },

        imgPreview: function(img) {
            console.log('this.data',this.data);
            if(typeof img.id !== 'undefined') {
                this.data.img = img.id;
                $('#img-view').html(template('img-tpl', img));
            }
        },
        select_goods:function(e){
            this.collection = new Collection({
                container: 'data-list',
                template: 'data-items',
                url: _global.url.api + 'promotion_goods_search',
                condition: {keyword:$("#keyword").val()},
                model: {
                    event: {

                        '.item-bind:click': 'addgoods',
                        '.show-online:click': 'setshow'
                    },
                    remove: function(e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            'content': '确定删除吗?',
                            ok: function() {
                                if(model.del()){
                                    _this.collection.reload();
                                };
                            }, cancel: function() {}
                        }).show(e.target);
                    },
                    addgoods:function(e){
                        e.preventDefault();
                        var _this =this;
                        var id =this.data.id;
                        var vals=new Array();
                        $(".goods_id").each(function(){
                            if($(this).val()){
                                vals.push($(this).val());
                            }
                        });
                        var goods_id=','+vals.join(",")+',';
                        if(goods_id.indexOf(','+id+',')!=-1){
                            Alert({msg: '请不要重复添加同一商品', type: 'error'});
                            return false;
                        }
                        $('#goods-item').append(template('goods-item-tpl',{goods_id:this.data.id, goods_name:this.data.name,price:this.data.price}));
                        $("#div_goods").show();
                        $('.goods-item-del').on('click', function(e) {
                            e.preventDefault();
                            $(this).parent().parent().remove();
                            $('.item-bind' +id).html('选择').removeClass('btn-success').addClass('btn-default');
                        });

                        $('.item-bind' +id).html('已选择').removeClass('btn-default').addClass('btn-success');
                    }

                },
                callback: function() {
                    loaded();
                }
            });
            this.collection.fetch();
        }

    };

    new index();

});